package parroty;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import parroty.client.Parroty;

import com.google.wave.api.*;
import com.google.wave.api.event.*;

public class ParrotyServlet extends AbstractRobot {

	private static Logger mst_oLogger = Logger.getLogger(ParrotyServlet.class
			.getName());

	@Override
	protected String getRobotName() {
		return "Parroty";
	}

	@Override
	protected String getRobotAvatarUrl() {
		return "http://www.bradyid.com/favicon.ico";
	}

	@Override
	protected String getRobotProfilePageUrl() {
		return "http://code.google.com/apis/wave/extensions/robots/java-tutorial.html";
	}

	@Override
	public void onWaveletSelfAdded(WaveletSelfAddedEvent event) {
		Blip blip = event.getWavelet().reply("\nHi everybody!");

		// Gadget gadget = new
		// Gadget("http://my-wave-gadgets.appspot.com/wave/NapkinGadget.xml");
		Gadget gadget = new Gadget(
				"http://wave-api.appspot.com/public/gadgets/areyouin/gadget.xml");

		gadget.setProperty("brc-app3-00@appspot.com:answer", "y");
		gadget.setProperty("brc-app3-00@appspot.com:order", "0");

		event.getWavelet().getRootBlip().append(gadget);

	}

	@Override
	public void onWaveletParticipantsChanged(
			WaveletParticipantsChangedEvent event) {
		for (String newParticipant : event.getParticipantsAdded()) {
			Blip blip = event.getWavelet().reply("\nHi : " + newParticipant);
		}
	}

	@Override
	public void onGadgetStateChanged(GadgetStateChangedEvent event) {
		// TODO Auto-generated method stub

		BlipContentRefs content = event.getBlip().at(event.getIndex());
		Gadget gadget = (Gadget) content.value();

		// Make sure this is the yes no gadget"
		if ("http://wave-api.appspot.com/public/gadgets/areyouin/gadget.xml"
				.equals(gadget.getUrl())) {
			String sWho = event.getModifiedBy();

			String sUserCurrentValue = gadget.getProperty(sWho + ":answer");
			String sParrotyNewAnswer = null;
			String sParrotyCurrentAnswer = gadget
			.getProperty("brc-app3-00@appspot.com:answer");
			if (sUserCurrentValue != null) {
				
				sParrotyNewAnswer = "y".equals(sUserCurrentValue) ? "n" : "y";
				
				Map<String, String> mapNewValues = new HashMap<String, String>();
				mapNewValues.put("brc-app3-00@appspot.com:answer", sParrotyNewAnswer);
				content.updateElement(mapNewValues);
			}
			Blip blip = event.getWavelet().reply(
					"\n" + sWho + " modified their answer to "
							+ sUserCurrentValue
							+ " Parroty is changing his answer from "+sParrotyCurrentAnswer+" to "
							+ sParrotyNewAnswer);
		}

	}

}
